package com.topisv.tms.web;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.topisv.tms.entity.Area;
import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.buyinfo.BuyInfo;
import com.topisv.tms.entity.buyinfo.BuyerInfo;
import com.topisv.tms.entity.buyinfo.BuyerInfoSum;
import com.topisv.tms.repository.buyinfo.BuyerInfoDao;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.buyinfo.BuyInfoService;
import com.topisv.tms.service.buyinfo.BuyerInfoService;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.AreaService;
import com.topisv.tms.tools.ExcelUtils;

import org.springside.modules.web.Servlets;

/**
 * 区域管理的Controller, 使用Restful风格的Urls:
 * 
 * List page : GET /area/ Create page : GET /area/create Create action : POST
 * /area/create Update page : GET /area/update/{id} Update action : POST
 * /area/update Delete action : GET /area/delete/{id}
 * 
 * @author Arthur
 */
@Controller
@RequestMapping(value = "/buyinfo")
public class BuyInfoController {


	private static final Logger logger = LoggerFactory.getLogger(BuyInfoController.class);

	@Autowired
	private BuyInfoService buyInfoService;
	
	@Autowired
	private BuyerInfoService buyerInfoService;

	@RequestMapping(value = "init")
	public String list() {
		return "buyinfo/buyinfo";
	}
	
	

	@RequestMapping(value = "/buy")
	public void buyinfo(ServletRequest request,HttpServletResponse response) {
		PrintWriter out=null;
		JSONObject json=null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			String sku=request.getParameter("sku");
			String buyer=request.getParameter("buyer");
			logger.info("sku======" + sku);
			
			BuyInfo buyInfo = buyInfoService.findBySku(sku);
			BuyerInfo buyerInfo = new BuyerInfo();
			buyerInfo.setUsername(buyer);
			buyerInfo.setSku(buyInfo.getSku());
			buyerInfo.setSkuName(buyInfo.getSkuName());
			buyerInfo.setPrice(buyInfo.getPrice());
			buyerInfo.setTime(new java.util.Date());
			
			if(buyInfo!=null)
			{
				buyerInfoService.save(buyerInfo);
				json.put("buyInfo", buyInfo);
				json.put("msg", "success");
			}
			else
			{
				json.put("msg", "error");
			}
			out.print(json);
			
			} catch (Exception e) {
				
				logger.error("error",e);
				json.put("msg", "error");
				out.print(json);
			}	
	}
	
	@RequestMapping(value = "/exportExcel")
	public void exportExcel(ServletRequest request,HttpServletResponse response) {
		FileInputStream f=null;
		OutputStream output=null;
/*		JSONObject json=null;
		PrintWriter out=null;*/
		try{
			//out = response.getWriter();
			//json = new JSONObject();
			Date now=new Date();
			DateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
			int count = 0;
		
			List<BuyerInfo> buyList = buyerInfoService.getAllBuyerInfo();
			List<BuyerInfoSum> sum = new ArrayList<BuyerInfoSum>();
		
			//把销售商品信息汇总到BuyerInfoSum类型的List中
			for(BuyerInfo buyerInfo:buyList){
				count = 0;
				for(BuyerInfoSum buyerInfoSum:sum){
					if(buyerInfo.getUsername().equals(buyerInfoSum.getUsername()) && 
							buyerInfo.getSku().equals(buyerInfoSum.getSku()) &&
							buyerInfo.getSkuName().equals(buyerInfoSum.getSku_name()) &&
							buyerInfo.getPrice().equals(buyerInfoSum.getPrice())){
						buyerInfoSum.setQty(buyerInfoSum.getQty() + 1);
						count += 1;
						break;
					}
				}
				if(count == 0){
					BuyerInfoSum buyerSum = new BuyerInfoSum();
					buyerSum.setUsername(buyerInfo.getUsername());
					buyerSum.setSku(buyerInfo.getSku());
					buyerSum.setSku_name(buyerInfo.getSkuName());
					buyerSum.setPrice(buyerInfo.getPrice());
					buyerSum.setQty(1);
					sum.add(buyerSum);
				}
			}
		   List<Object[]> list = new ArrayList<Object[]>();
		
		   for (int i = 0; i < sum.size(); i++) {
			   try {
				   BuyerInfoSum infoSum=sum.get(i);
				   Object[] obj = {
						i+1,
						infoSum.getUsername(),
						infoSum.getSku(),
						infoSum.getSku_name(),
						infoSum.getPrice(),
						infoSum.getQty(),
						null
				   };
				   list.add(obj);
			   } catch (Exception e) {
				   logger.error("error",e);
			   }
		   }
		
		/** 导出数据 */
		   String[] title = { "序号", "客户","SKU","商品货号", "商品价格","商品数量"};
		   String filepath = "商品销售表.xls";
		   String title_page="商品销售信息表";
		   ExcelUtils.writeExcel(title, filepath,title_page, df.format(now) , list); // 生成excel
		   
		   /** 把生成的excel文件读出字节返回给客户端 */
		   ((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename="+ new String(filepath.getBytes("gb2312"),"iso8859-1"));
		   f = new FileInputStream(ExcelUtils.TEMPPATH+filepath);
		   byte[] fb = new byte[f.available()];
		   f.read(fb);
		   ByteArrayInputStream bais = new ByteArrayInputStream(fb);
		   output =((HttpServletResponse)response).getOutputStream();
		   int by = 0;
		   while ((by = bais.read()) != -1) {
			   output.write(by);
		   }
		   output.flush();
		
	   } catch (Exception e) {
		   logger.error("error");
	   }finally{
		   if (output!=null) {
			   try { output.close(); } catch (IOException e) {logger.error("error",e);}
		   }
		   if (f!=null) {
			   try { f.close(); } catch (IOException e)  {logger.error("error",e);}
		   }
	   }
		//json.put("msg", "success");
		//out.print(json);
		
	}
}

	
